import 'package:dart_date/dart_date.dart';

import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:reactive_forms/reactive_forms.dart';
import 'package:sprintf/sprintf.dart';

import 'package:yt_devops/configs.dart';
import 'package:yt_devops/model/amap_poi.dart';
import 'package:yt_devops/model/install_provider_model.dart';
import 'package:yt_devops/model/user_model.dart';
import 'package:yt_devops/pages/site/site_list/site_list_model.dart';
import 'package:yt_devops/pages/tasks/create_repair_task/create_repair_task_model.dart';
import 'package:yt_devops/pages/tasks/task_list/task_list_controller.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/services/common/common_services.dart';
import 'package:yt_devops/services/site/site_services.dart';
import 'package:yt_devops/services/task/task_services.dart';
import 'package:yt_devops/user_entity_manager.dart';
import 'package:yt_devops/utils/constants/time_formated.dart';
import 'package:yt_devops/utils/enums.dart';
import 'package:yt_devops/utils/func_utils.dart';

import 'repair_task_operate_enum.dart';

class CreateRepairTaskController extends GetxController {
  CreateRepairTaskModel model = CreateRepairTaskModel();
  CommonServices commonServices = Get.find();
  TaskServices services = Get.find();
  SiteServices siteServices = SiteServices();
  TaskListController taskListController = Get.find();

  late FormGroup form;

  FormGroup buildForm() => fb.group(<String, Object>{
        'site': FormControl<SiteModel>(value: null),
        'name': FormControl<String>(value: ''),
        'orgId': FormControl<InstallProviderModel>(
            validators: [Validators.required], value: getCurInstallProvider()),
        'handlerBy': FormControl<UserModel>(
          validators: [Validators.required],
        ),
        'userId': FormControl<UserModel>(
          validators: [Validators.required],
        ),
        'phone': FormControl<String>(
          validators: [
            Validators.required,
          ],
        ),
        'remark': FormControl<String>(),
        'content': FormControl<String>(),
        'timeOfAppointment': FormControl<DateTime>(
          validators: [Validators.required],
        ),
        'map': FormControl<MapType>(
            validators: [Validators.required], value: MapType.amap),
        'address': FormControl<AmapPoi>(value: null),
        'descPicUrl': FormControl<List<String>>(value: []),
      });

  bool get isAdd =>
      operateType == RepairTaskTypeOperateEnum.update ? true : false;

  String get title => operateType == RepairTaskTypeOperateEnum.update
      ? sprintf(
          ResKey.commonEditSentence.tr, [ResKey.workOrderMaintenanceOrder.tr])
      : sprintf(ResKey.commonCreateSentence.tr,
          [ResKey.workOrderMaintenanceOrder.tr]);
  RepairTaskTypeOperateEnum operateType = RepairTaskTypeOperateEnum.create;

  int? taskId;

  @override
  void onInit() {
    if (Get.arguments != null && Get.arguments['type'] != null) {
      operateType = Get.arguments['type'];
      if (operateType == RepairTaskTypeOperateEnum.update) {
        taskId = Get.arguments['id'];
        loadDetail(taskId!);
      }
    }
    super.onInit();
  }

  @override
  void onReady() {
    if (operateType == RepairTaskTypeOperateEnum.createFromRepair) {
      initDataFromRepair();
    }
  }

  @override
  void onClose() {}

  initDataFromRepair() {
    var args = Get.arguments;
    taskId = args['id'];
    form.resetState({
      'site': ControlState<SiteModel>(
          value: SiteModel(siteId: args['siteId'], name: args['siteName']),
          disabled: true),
      'name': ControlState<String>(
        value: args['name'],
      ),
      'content': ControlState<String>(value: args['content']),
      'descPicUrl': ControlState<List<String>>(value: []),
      'orgId':
          ControlState<InstallProviderModel>(value: getCurInstallProvider()),
      'userId': ControlState<UserModel>(
          value: UserModel(userId: args['userId'], userName: args['userName']),
          disabled: true),
    });
  }

  // 当是安装商登录时，则获取改用户的安装商信息，并回填
  InstallProviderModel? getCurInstallProvider() {
    if (UserEntityManager().roleID == RoleType.installer.value) {
      var user = UserEntityManager().userModel;
      return InstallProviderModel(
          orgId: user.orgId, orgName: user.org?.orgName);
    } else {
      return null;
    }
  }

  Future<dynamic> getService(Map<String, dynamic> params) {
    if (operateType == RepairTaskTypeOperateEnum.create) {
      return services.createRepair(params);
    } else if (operateType == RepairTaskTypeOperateEnum.update) {
      params.putIfAbsent('id', () => taskId);
      return services.editRepair(params);
    } else {
      var data = {'id': taskId, 'maintenanceTask': params};
      return services.createRepairByReport(data);
    }
  }

  loadDetail(int id) => Configs.httpClient.requestWithLoading(() async {
        var params = {'id': id};
        var data = await services.getRepairTaskDetail(params);

        form.resetState({
          'site': ControlState<SiteModel>(
              value: SiteModel(siteId: data['siteId'], name: data['siteName'])),
          'name': ControlState<String>(
            value: data['name'],
          ),
          'orgId': ControlState<InstallProviderModel>(
            value: InstallProviderModel.fromJson(data),
          ),
          'handlerBy': ControlState<UserModel>(
            value: UserModel(
                userId: data['handlerBy'], userName: data['handlerName']),
          ),
          'userId': ControlState<UserModel>(
              value: UserModel(
                  userId: data['userId'], userName: data['userName'])),
          'phone': ControlState<String>(value: data['phone']),
          'remark': ControlState<String>(value: data['remark']),
          'content': ControlState<String>(value: data['content']),
          'timeOfAppointment': ControlState<DateTime>(
              value: FuncUtils.isEmpty(data['timeOfAppointment'])
                  ? null
                  : DateTime.parse(data['timeOfAppointment']!)),
          'map': ControlState<MapType>(
              value: MapType.values.firstWhereOrNull(
                      (element) => element.value == data['map']) ??
                  MapType.amap),
          'address': ControlState<AmapPoi>(
            value: data['latitude'] == null
                ? null
                : AmapPoi(
                    formattedAddress: data['address'],
                    latitude: data['latitude'],
                    longitude: data['longitude']),
          ),
          'descPicUrl': ControlState<List<String>>(
              value: FuncUtils.isEmpty(data['descPicUrl'])
                  ? []
                  : data['descPicUrl'].split(','))
        });
        update();
      });

  void commit(FormGroup form) =>
      Configs.httpClient.requestWithLoading(() async {
        if (!form.valid) {
          return;
        }
        var params = form.rawValue;
        var address = form.control('address').value;
        params
          ..putIfAbsent('longitude', () => address.longitude)
          ..putIfAbsent('latitude', () => address.latitude)
          ..putIfAbsent('siteId', () => form.control('site').value.siteId);
        params['map'] = (form.control('map').value as MapType).value;
        params['address'] = address.formattedAddress;
        params['handlerBy'] = form.control('handlerBy').value.userId;
        params['orgId'] = form.control('orgId').value.orgId;
        params['userId'] = form.control('userId').value.userId;
        params['timeOfAppointment'] =
            (form.control('timeOfAppointment').value as DateTime)
                .format(TimeFormated.dateTimeFromated);
        params['descPicUrl'] = form.control('descPicUrl').value.join(',');
        params.remove('site');

        await getService(params);

        EasyLoading.showSuccess(ResKey.operateSuccessTip.tr).then((value) {
          Get.back(result: true);
          taskListController.refreshRepair();
        });
      });
}
